﻿using System;
using System.Web;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Web.Script.Serialization;

namespace PeachLite.Helpers
{
    public static class JSONHelper
    {
        public static string GetJSON<T>(T t)
        {
            if (t == null) return string.Empty;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            StringBuilder result = new System.Text.StringBuilder();
            serializer.Serialize(t, result);
            return result.ToString();
        }

        public static string GetJSON(object o)
        {
            if (o == null) return string.Empty;

            JavaScriptSerializer s = new JavaScriptSerializer();
            return s.Serialize(o);
        }

        public static T GetEntity<T>(string json)
        {
            if (!string.IsNullOrEmpty(json))
            {
                try
                {
                    JavaScriptSerializer serializer = new JavaScriptSerializer();
                    return serializer.Deserialize<T>(json);
                }
                catch
                {
                    return default(T);
                }
            }
            else
            {
                return default(T);
            }
        }
    }
}